import java.util.*;

public class WeightRandom<K, V extends Number> {
    private TreeMap<Double, K> weightMap = new TreeMap<>();

    public WeightRandom(Map<K, V> map) {
        for (Map.Entry<K, V> kvEntry : map.entrySet()) {
            K key = kvEntry.getKey();
            V value = kvEntry.getValue();
            if (key != null && value != null && value.intValue() != 0) {
                double lastWeight = this.weightMap.size() == 0 ? 0 : this.weightMap.lastKey().doubleValue();//统一转为double
                this.weightMap.put(value.doubleValue() + lastWeight, key);//权重累加
            }
        }
    }

    public K random() {
        double randomWeight = this.weightMap.lastKey() * Math.random();
        SortedMap<Double, K> tailMap = this.weightMap.tailMap(randomWeight, false);
        return this.weightMap.get(tailMap.firstKey());
    }

    static class LuckDrawPrizeDto{
        private Integer id;
        private String name;
        private Integer sort;
        private Integer probability;

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Integer getSort() {
            return sort;
        }

        public void setSort(Integer sort) {
            this.sort = sort;
        }

        public Integer getProbability() {
            return probability;
        }

        public void setProbability(Integer probability) {
            this.probability = probability;
        }
    }

    public static void main(String[] args) {
        Map<LuckDrawPrizeDto, Integer> map = new HashMap<>();
        ArrayList<LuckDrawPrizeDto> luckDrawPrizeDtoList = new ArrayList<>();
        LuckDrawPrizeDto luckDrawPrizeDto1 = new LuckDrawPrizeDto();
        luckDrawPrizeDto1.setId(12);
        luckDrawPrizeDto1.setProbability(20);
        luckDrawPrizeDtoList.add(luckDrawPrizeDto1);
        LuckDrawPrizeDto luckDrawPrizeDto2 = new LuckDrawPrizeDto();
        luckDrawPrizeDto2.setId(11);
        luckDrawPrizeDto2.setProbability(20);
        luckDrawPrizeDtoList.add(luckDrawPrizeDto2);
        LuckDrawPrizeDto luckDrawPrizeDto3 = new LuckDrawPrizeDto();
        luckDrawPrizeDto3.setId(123);
        luckDrawPrizeDto3.setProbability(60);
        luckDrawPrizeDtoList.add(luckDrawPrizeDto3);

        for (LuckDrawPrizeDto luckDrawPrizeDto : luckDrawPrizeDtoList) {
            Integer probability = luckDrawPrizeDto.getProbability();
            map.put(luckDrawPrizeDto, probability);
        }
        WeightRandom weightRandom = new WeightRandom(map);
        LuckDrawPrizeDto random = (LuckDrawPrizeDto) weightRandom.random();
        System.out.println(random);

        Deque<String> deque = new LinkedList<>();
        deque.peek();
    }

}